<template>
  <div>
    <van-nav-bar
    title="更新昵称"
    left-text="取消"
    right-text="保存"
    @click-left="$emit('click-left')"
    @click-right="onClickRight"
    />
    <van-field
      v-model="nickName"
      autosize
      type="textarea"
      maxlength="7"
      placeholder="请输入新的昵称"
      show-word-limit
    />
  </div>
</template>

<script>
import { updateProfile } from '@/api/user.js'
export default {
  name: 'update-name',
  data () {
    return {
      nickName: ''
    }
  },
  props: {
    value: {
      type: String,
      required: true
    }
  },
  created () {
    this.nickName = this.value
  },

  methods: {
    async onClickRight () {
      if (this.nickName.trim() === '') return this.$toast('亲，情书合法的昵称')
      try {
        await updateProfile({
          name: this.nickName
        })
        this.$toast('昵称更新成功')
        this.$emit('click-left')
        this.$emit('input', this.nickName)
      } catch (err) {
        console.dir(err)
        if (err.response && err.response.status === 400) {
          return this.$toast('昵称被占用')
        }
        this.$toast('更新失败')
      }
    }
  }
}
</script>

<style scoped lang='less'>

</style>
